﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using RoadFlow.Utility;

namespace RoadFlow.Mvc.Areas.RoadFlowCoreApi.Controllers
{
    [Route("RoadFlowCoreApi/[controller]")]
    [ApiController]
    public class FlowController : ControllerBase
    {
        /// <summary>
        /// 得到一个系统的所有流程
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetFlows")]
        [ApiValidate]
        public string GetFlows()
        {
            var reader = new StreamReader(Request.Body);
            string json = reader.ReadToEnd();
            JObject jObject_params = null;
            try
            {
                jObject_params = JObject.Parse(json);
            }
            catch { }
            string systemCode = jObject_params.Value<string>("systemcode");
            if (systemCode.IsNullOrEmpty())
            {
                return ApiTools.GetErrorJson("参数systemcode为空");
            }
            var systemId = new Business.FlowApiSystem().GetIdBySystemCode(systemCode);
            if (systemId.IsEmptyGuid())
            {
                return ApiTools.GetErrorJson("未找到systemcode对应的系统");
            }
            var flows = new Business.Flow().GetAll().FindAll(p => p.SystemId == systemId);
            JObject jObject = ApiTools.GetJObject();
            jObject.Add("data", JArray.FromObject(flows));
            return jObject.ToString(Newtonsoft.Json.Formatting.None);
        }

        /// <summary>
        /// 得到一个流程Json
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetFlowJson")]
        [ApiValidate]
        public string GetFlowJson()
        {
            var reader = new StreamReader(Request.Body);
            string json = reader.ReadToEnd();
            JObject jObject_params = null;
            try
            {
                jObject_params = JObject.Parse(json);
            }
            catch { }
            string systemCode = jObject_params.Value<string>("systemcode");
            if (systemCode.IsNullOrEmpty())
            {
                return ApiTools.GetErrorJson("参数systemcode为空");
            }
            var systemId = new Business.FlowApiSystem().GetIdBySystemCode(systemCode);
            if (systemId.IsEmptyGuid())
            {
                return ApiTools.GetErrorJson("未找到systemcode对应的系统");
            }
            string flowId = jObject_params.Value<string>("flowid");
            var flow = new Business.Flow().GetAll().Find(p => p.SystemId == systemId && p.Id == flowId.ToGuid());
            if (null == flow)
            {
                return ApiTools.GetErrorJson("未找到流程");
            }
            JObject jObject = ApiTools.GetJObject();
            jObject.Add("data", flow.RunJSON.IsNullOrWhiteSpace() ? flow.DesignerJSON : flow.RunJSON);
            return jObject.ToString(Newtonsoft.Json.Formatting.None);
        }

        /// <summary>
        /// 得到一个流程一个步骤的表单地址
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetStepFormAddress")]
        [ApiValidate]
        public string GetStepFormAddress()
        {
            var reader = new StreamReader(Request.Body);
            string json = reader.ReadToEnd();
            JObject jObject_params = null;
            try
            {
                jObject_params = JObject.Parse(json);
            }
            catch { }
            string systemCode = jObject_params.Value<string>("systemcode");
            if (systemCode.IsNullOrEmpty())
            {
                return ApiTools.GetErrorJson("参数systemcode为空");
            }
            string flowId = jObject_params.Value<string>("flowid");
            string stepId = jObject_params.Value<string>("stepid");
            var flowRunModel = new Business.Flow().GetFlowRunModel(flowId.ToGuid());
            if (null == flowRunModel)
            {
                return ApiTools.GetErrorJson("未找到流程运行时");
            }
            var step = flowRunModel.Steps.Find(p => p.Id == stepId.ToGuid());
            if (null == step)
            {
                return ApiTools.GetErrorJson("未找到步骤");
            }
            JObject jObject = ApiTools.GetJObject();
            Business.AppLibrary appLibrary = new Business.AppLibrary();
            if (step.StepForm.Id.IsNotEmptyGuid())
            {
                var appModel = appLibrary.Get(step.StepForm.Id);
                if (null != appModel)
                {
                    jObject.Add("address", appModel.Address);
                }
            }
            if (step.StepForm.MobileId.IsNotEmptyGuid())
            {
                var appModel = appLibrary.Get(step.StepForm.MobileId);
                if (null != appModel)
                {
                    jObject.Add("addressmobile", appModel.Address);
                }
            }
            return jObject.ToString(Newtonsoft.Json.Formatting.None);
        }

        /// <summary>
        /// 得到一个流程的发送步骤
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetSendSteps")]
        [ApiValidate]
        public string GetSendSteps()
        {
            var reader = new StreamReader(Request.Body);
            string json = reader.ReadToEnd();
            JObject jObject_params = null;
            try
            {
                jObject_params = JObject.Parse(json);
            }
            catch { }
            string systemCode = jObject_params.Value<string>("systemcode");
            if (systemCode.IsNullOrEmpty())
            {
                return ApiTools.GetErrorJson("参数systemcode为空");
            }
            string flowId = jObject_params.Value<string>("flowid");
            string stepId = jObject_params.Value<string>("stepid");
            string taskId = jObject_params.Value<string>("taskid");
            string userId = jObject_params.Value<string>("userid");
            bool isFreeSend = "true".EqualsIgnoreCase(jObject_params.Value<string>("freesend"));//是否是自由发送
            var flowRunModel = new Business.Flow().GetFlowRunModel(flowId.ToGuid());
            if (null == flowRunModel)
            {
                return ApiTools.GetErrorJson("未找到流程运行时");
            }
            if (!stepId.IsGuid(out Guid stepGuid))
            {
                stepGuid = flowRunModel.FirstStepId;
            }
            Business.FlowTask flowTask = new Business.FlowTask();
            Guid groupId = Guid.Empty;
            string instanceId = string.Empty;
            bool isMobile = false;
            if (taskId.IsGuid(out Guid taskGuid))
            {
                var task = flowTask.Get(taskGuid);
                if (null != task)
                {
                    groupId = task.GroupId;
                    instanceId = task.InstanceId;
                }
            }
            
            var (html, message, sendSteps) = flowTask.GetNextSteps(flowRunModel, stepGuid, groupId, taskGuid, instanceId, userId.ToGuid(), isFreeSend, isMobile);
            JObject jObject = ApiTools.GetJObject();
            JArray jArray = new JArray();
            foreach (var step in sendSteps)
            {
                JObject jObject1 = new JObject
                {
                    { "id", step.Id },
                    { "name", step.Name },
                    { "users", step.RunDefaultMembers },
                    { "note", step.Note }
                };
                jArray.Add(jObject1);
            }
            jObject.Add("data", jArray);
            return jObject.ToString(Newtonsoft.Json.Formatting.None);
        }

        /// <summary>
        /// 得到退回的步骤
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetBackSteps")]
        [ApiValidate]
        public string GetBackSteps()
        {
            var reader = new StreamReader(Request.Body);
            string json = reader.ReadToEnd();
            JObject jObject_params = null;
            try
            {
                jObject_params = JObject.Parse(json);
            }
            catch { }
            if (null == jObject_params)
            {
                return ApiTools.GetErrorJson("参数不是有效的json字符串(" + json + ")");
            }
            string systemCode = jObject_params.Value<string>("systemcode");
            string userId = jObject_params.Value<string>("userid");
            if (systemCode.IsNullOrEmpty())
            {
                return ApiTools.GetErrorJson("参数systemcode为空");
            }
            string taskId = jObject_params.Value<string>("taskid");
            if (!taskId.IsGuid(out Guid taskGuid))
            {
                return ApiTools.GetErrorJson("参数taskid不是有效的Guid类型字符串");
            }
            Business.FlowTask flowTask = new Business.FlowTask();
            var currentTask = flowTask.Get(taskGuid);
            if (null == currentTask)
            {
                return ApiTools.GetErrorJson("未找到taskid对应的任务实体");
            }
            var flowRunModel = new Business.Flow().GetFlowRunModel(currentTask.FlowId);
            if (null == flowRunModel)
            {
                return ApiTools.GetErrorJson("未找到流程运行时");
            }
            if (!userId.IsGuid(out Guid userGuid))
            {
                userGuid = currentTask.ReceiveId;
            }

            var (html, message, backSteps) = flowTask.GetBackSteps(currentTask.FlowId, currentTask.StepId, currentTask.GroupId, currentTask.Id, currentTask.InstanceId, userGuid);
            JObject jObject = ApiTools.GetJObject();
            JArray jArray = new JArray();
            foreach (var backStep in backSteps)
            {
                JObject jObject1 = new JObject
                {
                    { "id", backStep.Id },
                    { "name", backStep.Name },
                    { "users", backStep.RunDefaultMembers },
                    { "note", backStep.Note }
                };
                jArray.Add(jObject1);
            }
            jObject.Add("data", jArray);
            return jObject.ToString(Newtonsoft.Json.Formatting.None);
        }
    }
}